package icraf.carbon.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class Config {

	public enum ConfigItem {
		ACTIVE_FOLDER("active_folder", ""), 
		PRECISION_MIN("precision_min", "2"),
		PRECISION_MED("precision_med", "4"),
		PRECISION_MAX("precision_max", "6");

		private String key;
		private String value = "";
		private String defValue;

		ConfigItem(String key, String defValue) {
			this.key = key;
			this.defValue = defValue;
			this.value = defValue;
		}

		public String getKey() {
			return key;
		}

		public String getValueString() {
			return value;
		}
		
		public double getValueDouble() {
			double d = Double.NaN;
			try {
				d = Double.parseDouble(defValue);
			} catch (NumberFormatException e) {
			}
			try {
				if(value != null)
					d = Double.parseDouble(value);
			} catch (NumberFormatException e) {
			}
			
			return d;
		}

		public void setValue(String value) {
			this.value = value;
		}
	}
	
	private static String fileName = "config.properties";
	private String filePath = "";

	public Config() {
		new File(System.getenv("APPDATA")+"/abacus").mkdir();
		filePath = System.getenv("APPDATA")+"/abacus/"+fileName;
	}
	
	public void saveConfig() {
    	Properties prop = new Properties();
    	try {
    		//set the properties value
    		for(ConfigItem c: ConfigItem.values()) {
    			prop.setProperty(c.key, c.value);
    		}
    		prop.store(new FileOutputStream(filePath), null);
 
    	} catch (IOException ex) {
    		//ex.printStackTrace();
        }
    }
	
	public void loadConfig() {
    	Properties prop = new Properties();
 
    	try {
            //load a properties file
    		prop.load(new FileInputStream(filePath));
    		for(ConfigItem c: ConfigItem.values()) {
    			String val = prop.getProperty(c.key);
    			if(val != null)
    				c.setValue(val);
    		}
    	} catch (IOException ex) {
    		//ex.printStackTrace();
        }
 
    }
}
